﻿// $Id: TypeMapperSettingsEditor.cs 68 2008-05-09 16:11:33Z nvivo $

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.IO;
using System.Text;
using System.Windows.Forms;
using DBLGen.UI;

namespace DBLGen.Plugins.Batch
{
	public partial class TypeMapperSettingsEditor : PluginSettingsEditor
	{
		public TypeMapperSettingsEditor()
		{
			InitializeComponent();
		}

		private void TypeMapperSettingsEditor_LoadingSettings(object sender, EventArgs e)
		{
			TypeMapperSettings settings = (TypeMapperSettings)base.Settings;

			chkUseNullables.Checked = settings.UseNullables;

			if (String.IsNullOrEmpty(settings.CustomAttribute))
				rbUseType.Checked = true;
			else
			{
				rbUseCustom.Checked = true;
				txtCustomAttribute.Text = settings.CustomAttribute;
			}

		}

		private void TypeMapperSettingsEditor_SavingSettings(object sender, EventArgs e)
		{
			TypeMapperSettings settings = (TypeMapperSettings)base.Settings;

			settings.Mapping = GetCurrentMapping();
			settings.UseNullables = chkUseNullables.Checked;

			if (rbUseType.Checked)
				settings.CustomAttribute = null;
			else
				settings.CustomAttribute = txtCustomAttribute.Text;
		}

		private TypeMapping GetCurrentMapping()
		{
			string path = txtMappingFilePath.Text;

			if (File.Exists(path))
				return TypeMapping.LoadFromXml(path);
			else
				return null;
		}

		private void rbUseType_CheckedChanged(object sender, EventArgs e)
		{
			txtCustomAttribute.Enabled = false;
		}

		private void rbUseCustom_CheckedChanged(object sender, EventArgs e)
		{
			txtCustomAttribute.Enabled = true;

			if (txtCustomAttribute.Text == String.Empty)
			{
				TypeMapping mapping = GetCurrentMapping();
				txtCustomAttribute.Text = mapping.CustomAttribute ?? "customtype";
			}
		}

		private void btnBrowse_Click(object sender, EventArgs e)
		{
			string entryPath = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
			string defaultPath = Path.Combine(entryPath, "TypeMappings");
			
			using (OpenFileDialog dlg = new OpenFileDialog())
			{
				dlg.InitialDirectory = defaultPath;

				if (dlg.ShowDialog() == DialogResult.OK)
					txtMappingFilePath.Text = dlg.FileName;
			}
		}
	}
}
